# -*- coding: utf-8 -*-
# Auther : 风雪
# Date : 2023/12/7 23:02
# File : db.py


import pymysql
import pymongo
from bson import ObjectId

from f6zhishu.settings import MONGO_HOST, MONGO_PORT, MONGO_USER, MONGO_PASSWORD, MONGO_DATABASE, MONGO_TABLE


class MYSQLDB:
    def __init__(self, host, port, user, password, database, charset):
        self.host = host
        self.port = port
        self.user = user
        self.password = password
        self.database = database
        self.charset = charset

    def connect(self):
        self.connection = pymysql.connect(
            host=self.host,
            port=self.port,
            user=self.user,
            password=self.password,
            database=self.database,
            charset=self.charset,
            cursorclass=pymysql.cursors.DictCursor
        )

    # def insert_car_batch_record(self,table:str='car_batch_record'):
    #     try:
    #         with self.connection.cursor() as cursor:
    #             sql=f"INSERT INTO {table} ({},)"


class MongoDb:
    def __init__(self, host=MONGO_HOST, port=MONGO_PORT, user=MONGO_USER, password=MONGO_PASSWORD):
        self.host = host
        self.port = port
        self.username = user
        self.password = password

        self.db_set = self.connect()

    def connect(self):
        if self.username is None or self.password is None:
            db_url = f"mongodb://{self.host}:{self.port}/"
        else:
            db_url = f"mongodb://{self.username}:{self.password}@{self.host}:{self.port}/"
        self.connection = pymongo.MongoClient(host=db_url)
        db = self.connection[MONGO_DATABASE]
        db_set = db[MONGO_TABLE]

        return db_set

    def insert_one(self, data: dict) -> dict:
        if not data:
            return {'code': 0, 'msg': '传入数据为空', "data": None}
        try:
            result = self.db_set.insert_one(data)
            return {"code": 1, 'msg': 'ok', "data": {"id": str(result.inserted_id)}}
        except Exception as e:
            return {'code': -1, 'msg': str(e), "data": None}

    def insert_convention_one(self, id_: str, data: dict, data_type: str) -> dict:
        """
        插入产品的数据
        :param id_:mongo的objid
        :param data: 数据
        :param data_type:类型  常规保养=1 车身电器=2 发动机系统=3 车辆详情=4
        :return:
        """
        id_obj = {'_id': ObjectId(id_)}
        if not data:
            return {'code': 0, 'msg': '传入数据为空', "data": None}
        if data_type == "常规保养":
            type_str = "常规保养"
        elif data_type == "车身电器":
            type_str = "车身电器"
        elif data_type == "发动机系统":
            type_str = "发动机系统"
        elif data_type == "车辆详情":
            type_str = "车辆详情"
        elif data_type == "底盘悬挂系统":
            type_str = "底盘悬挂系统"
        elif data_type == "其他":
            type_str = "其他"
        else:
            return {'code': -100, 'msg': '传入数据 data_type 参数错误，参数范围[1,2,3,4]', "data": None}
        try:

            # if next(iter(data)) == '蓄电池':
            #     result = self.db_set.update_one(id_obj,{"$push": {"data.常规保养.蓄电池": data["data"]["常规保养"]["蓄电池"]}})
            # else:
            result = self.db_set.update_one(id_obj, {"$push": {type_str: data}})
            # 如果返回值 update_num不是1就有问题
            return {"code": 1, 'msg': 'ok', "data": {"update_num": str(result.modified_count)}}
        except Exception as e:
            return {'code': -1, 'msg': str(e), "data": None}


if __name__ == '__main__':
    test_mongo = MongoDb()
    xxx = test_mongo.insert_one({'vin': 'xxxxxx', 'time': "2023-12-08"})
    id_ = xxx['data']['id']
    print(id_)
    up = test_mongo.insert_convention_one(id_=id_, data={"蓄电池": [{'bn1': 'xxx'}]}, data_type=1)
    print(xxx)
    print(up)
